<script type="text/javascript" src="{{base_url()}}lib/tokeninput/jquery.tokeninput.js"></script>
<link rel="stylesheet" href="{{base_url()}}lib/tokeninput/token-input.css" type="text/css" />
<link rel="stylesheet" href="{{base_url()}}lib/tokeninput/token-input-facebook.css" type="text/css" />        

<span class="debug"></span>
<div style="padding-right: 22px;padding-left: 20px;background: #f1f1f1"
         id="id-deal-jqxgrid"
         >
    <table style="margin-bottom: 20px">
        <tr>
            <td>Từ</td>
            <td>
                <div style='float: left; margin-top: 0px;margin-bottom: 0px' id='jqxDateTimeInputFrom'></div>
            </td>
            <td>đến</td>
            <td>
                <div style='float: left; margin-top: 0px;margin-bottom: 0px' id='jqxDateTimeInputTo'></div>
            </td>
            <td>
                <input type="button" class="classic-button" onclick="reportFRM.reloadreport()" id="report-view" value="Xem"/>
            </td>
            <td>
                <input type="button" class="classic-button tofullscreen" onclick="swichtofullscreen();" id="report-view" value="Phóng to"/>
                <input type="button" class="classic-button hidden closefullscreen" onclick="closefullscreen();" id="report-view" value="Thu nhỏ"/>
            </td>
        </tr>
        <tr>
            <td colspan="2" style="padding-top: 12px">
                <input type="text" id="listProduct" name="blah" style="width: 100%"  value=""/>
            </td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>
    
    <div id="jqxWidget" style="position: relative;">
        <div id="jqxgrid"></div>
        
    </div>
    
</div>
<script>
    function swichtofullscreen(){
        $("#id-content-page").css({position:'fixed',left:0,top:30,bottom:0,right:0,width:'100%'});
        $('#jqxgrid').jqxGrid({ width: '100%' }); 
        $(".closefullscreen").show();
        $(".tofullscreen").hide();
        $('#grid').jqxGrid('refresh');
    }
    function closefullscreen(){
        $("#id-content-page").css({position:'relative',left:0,top:0,bottom:0,right:0,width:'960px'});
        $('#jqxgrid').jqxGrid({ width: '920px' }); 
        $(".closefullscreen").hide();
        $(".tofullscreen").show();
        $('#grid').jqxGrid('refresh');
    }
    $(document).ready(function () {
        reportFRM.init();
        $("#listProduct").tokenInput("{{base_url()}}admin-planners/report/tokenProduct", {
            resultsFormatter: function(item){ return "<li><div style='width:40px;color:#000;float:left;'>" + item.ProductID + "</div> " + item.ProductName + "</li>" },
            tokenFormatter: function(item) { return "<li>" + item.ProductName + "</li>" },
            propertyToSearch: "ProductID",
            hintText:"Nhập để tìm sản phẩm",
            minChars: 2,
            tokenLimit: 10
        });
    });
    
    var reportFRM = (function () {
        //Adding event listeners
        function _reloadreport(){
            var products=$('#listProduct').tokenInput("get");
            if(products.length==0){
                alert("Vui lòng chọn sản phẩm");
                return;
            }
            var sproduct="";
            for(var i=0;i<products.length;i++){
                sproduct+=products[i].ProductID+" ";
            }
            sproduct+="0";
            
            var dFrom= new Date($('#jqxDateTimeInputFrom').jqxDateTimeInput('getDate'));
            var dTo= new Date($('#jqxDateTimeInputTo').jqxDateTimeInput('getDate')); 
            var sfrom=dFrom.getFullYear()+"-"+(dFrom.getMonth()+1)+"-"+dFrom.getDate();
            var sto=dTo.getFullYear()+"-"+(dTo.getMonth()+1)+"-"+dTo.getDate();
            $("h1.page-tit").html("Báo cáo tổng hợp doanh thu theo thời gian ("+ sfrom +" đến "+sto+")");
            $("#jqxgrid").jqxGrid( { source: _getsource(sproduct,sfrom,sto) });

        }
        function _addEventListeners() {
            
            

        };
        //Creating all page elements which are jqxWidgets
        function _createElements() {
            var theme=reportFRM.config.theme;
            $("#jqxDateTimeInputFrom,#jqxDateTimeInputTo").jqxDateTimeInput({ width: '270px', height: '25px', theme: theme ,formatString: 'yyyy-MM-dd'});
            
        };
        //Creating the demo window
        function _createWindow() {
            var theme=reportFRM.config.theme;
            
        };
        function _getsource(productid,from,to){
            var source ={
                datatype: "json",
                datafields: [
                        { name: 'ProductID', type: 'string'},
                        { name: 'ProductName', type: 'string'},
                        { name: 'Supplier',type:'string'},
                        { name: 'OrderID', type: 'string'},
                        { name: 'CustomerName',type:'string'},
                        { name: 'UnitPrice',type:'float'},
                        { name: 'Quantity',type:'int'},
                        { name: 'OrderCash',type:'float'},
                        { name: 'UnitsOnOrder',type:'float'},
                        { name: 'Monney',type:'float'},
                        { name: 'ShipCash',type:'float'},
                        { name: 'OrderDate',type:'date'}
                ],
                url: '{{base_url()}}admin-planners/report/jqgrid_data_synthesis_from_to_detail/'+productid+"/"+from+'/'+to,
                filter: function(){
                        $("#jqxgrid").jqxGrid('updatebounddata');
                },
                sort: function(){
                        // update the grid and send a request to the server.
                        $("#jqxgrid").jqxGrid('updatebounddata');
                },
                root: 'Rows',
                beforeprocessing: function(data){		
                        source.totalrecords = data[0].TotalRows;					
                }
            };	

            var dataadapter = new $.jqx.dataAdapter(source, {
                            loadError: function(xhr, status, error)
                            {
                                $('#window-error').jqxWindow('setContent',"<b>Status</b>:"+xhr.status+"<br/><b>ThrownError</b>:"+error+"<br/>");
                                $('#window-error').jqxWindow('open');
                            }
                    }
            );
            return dataadapter;
        }
        //create jqgrid
        function _createGrid() {
            var theme=reportFRM.config.theme;
            // initialize jqxGrid
            $("#jqxgrid").jqxGrid(
            {	
                width:'920px',
                source: _getsource(0,'{{date("Y-m-d")}}','{{date("Y-m-d")}}'),//dataadapter,
                theme: theme,
                showstatusbar: true,
                statusbarheight: 40,
                showaggregates: true,
                autoheight: true,
                ready: function () {
                },
                rendergridrows: function(obj)
                {
                    return obj.data;    
                },
                columns: [
                        { text: 'Mã sản phẩm'    , datafield: 'ProductID',width:80 },
                        { text: 'Sản phẩm'  , datafield: 'ProductName' ,minwidth:120 , aggregates: ['count'] },
                        { text: 'Nhà cung cấp'    , datafield: 'Supplier' ,minwidth:120},
                        { text: 'Mã đơn hàng'    , datafield: 'OrderID' ,width:80},
                        { text: 'Ngày đặt hàng'    , datafield: 'OrderDate' ,width:80,cellsformat: 'yyyy-MM-dd'},
                        { text: 'Khách hàng'      , datafield: 'CustomerName' ,width:100 ,cellsalign: 'right'},
                        { text: 'Giá bán'     , datafield: 'UnitsOnOrder' ,minwidth:100 , cellsalign: 'right',cellsformat: 'c0' },
                        { text: 'Số lượng' , datafield: 'Quantity' ,width:80 ,cellsalign: 'right' ,aggregates: ['sum']},
                        { text: 'Thành tiền'        , datafield: 'Monney' ,width:100,cellsalign: 'right' ,cellsformat: 'c0',aggregates: ['sum', 'avg'] },
                        { text: 'Phí giao hàng'        , datafield: 'ShipCash' ,width:100,cellsalign: 'right' ,cellsformat: 'c0',aggregates: ['sum', 'avg'] },
                        { text: 'Tổng thành tiền'        , datafield: 'OrderCash' ,width:100,cellsalign: 'right' ,cellsformat: 'c0',aggregates: ['sum', 'avg'] }
                ]
            });

        };
        return {
            config: {
                dragArea: null,
                theme: 'classic'
            },
            setting: function () {
                $('#window-setting').jqxWindow('open');
            },
            init: function () {
                //Creating all jqxWindgets except the window
                _createElements();
                _createWindow();
                //Adding jqxGrid
                _createGrid();
                //Attaching event listeners
                _addEventListeners();
            },
            reloadreport:function () {_reloadreport()}
        };
    } ());

</script>